import os
import sys
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__) + '/../'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'keepback.settings')
import django
django.setup()

from home.models import Course
from elasticsearch import Elasticsearch

es = Elasticsearch(['http://localhost:9200'])

def sync_courses():
    courses = Course.objects.all()
    for course in courses:
        doc = {
            "id": course.id,
            "name": course.name,
            "difficulty": course.difficulty,
            "part": course.part,
            "duration": course.duration,
            "property": course.property,
            "feature": course.feature,
            "equipment": course.equipment
        }
        # 如果有created_at字段，格式化
        if hasattr(course, 'created_at') and course.created_at:
            doc["created_at"] = course.created_at.strftime('%Y-%m-%dT%H:%M:%S')
        es.index(index="courses", id=course.id, document=doc)
    print(f"已同步 {courses.count()} 门课程到 ES")

if __name__ == "__main__":
    sync_courses() 